import { toLogin } from './public'
import {Local} from '@/utils/storage'
export const authRequest = <T>(options: RequestOption, showLoading = true) => {
  return new Promise<Result<T>>((resolve, reject) => {
    options.url =  import.meta.env.VITE_API_BASE_URL + options.url
    //const token = Local.get('access_token') ? Local.get('access_token') : ''
    const token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
    options.header = {
      'content-type': 'application/json',
      Authorization: token ? `Bearer ${token}` : '',
      ...options.header
    }
    if (showLoading) {
      uni.showLoading({
        title: '玩命加载中...',
        mask: true
      })
    }
    uni.request({
      ...options,
      success(res: any) {
        if (res.statusCode == 401) {
          toLogin()
          return
        } else if (res.statusCode !== 200) {
          setTimeout(() => {
            uni.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 3000
            })
          }, 1000)
          console.log('options', options)
          console.log('res', res)
          reject(`服务器异常${options.url}`)
        }
        const data = res.data as Result<T>
        resolve(data as Result<T>)
      },
      fail: (err: any) => {
        console.error('❌ 请求失败：', err) // 🔍 看看有没有失败
        reject(err)
      },
      complete() {
        uni.stopPullDownRefresh()
        uni.hideLoading()
      }
    })
  })
}
